package io.gitee.pkmer.util;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:1193094618@qq.com">pkmer</a>
 * <br>
 * <a href = "https://gitee.com/pkmer/sonatype-central-publisher">Code Repository</a>
 * At 2024/8/26
 */
public class StrUtils {

    public static final int fiveBitUnit = 5;

    public static byte[] getBytesUtf8(final String string){
        return getBytes(string, StandardCharsets.UTF_8);
    }

    public static String bytesToStr(byte[] bytes){
        return new String(bytes,StandardCharsets.UTF_8);
    }

    /**
     * Calls String.getBytes(Charset)
     * Params:
     * @param str – The string to encode (if null, return null).
     * @param charset – The Charset to encode the String
     * @return  the encoded bytes
     */
    public static byte[] getBytes(final String str, Charset charset){
        return str == null ? null:str.getBytes(charset);
    }

    /**
     * 字符串转换为base32 5bit 一组
     * 40bit 5 8bit
     * <a href="https://www.ietf.org/rfc/rfc4648.txt">Base32 RFC</a>
     *
     * @param binaryStr 二进制字符串
     * @return List
     */
    public static List<String> getBase32Group(String binaryStr) {

        final String ZEROS = "00000";

        List<String> groups = new ArrayList<>();
        int len = binaryStr.length();

        for (int i = 0; i < len; i += fiveBitUnit) {
            if (i + fiveBitUnit < len) {
                groups.add(binaryStr.substring(i, i + fiveBitUnit));
            } else {
                // bits with value zero are added (on the right)
                String g = binaryStr.substring(i) + ZEROS.substring(0, fiveBitUnit - (len - i));
                groups.add(g);
            }
        }
        return groups;
    }

    /**
     * 将数字转化为8bit字符串
     *
     * @param num 数字
     * @return 二进制字符串
     */
    public static String toBinaryStr(int num) {
        return String.format("%8s", Integer.toBinaryString(num)).replace(' ', '0');
    }
}
